<?php
class AdminController extends Controller {
	
	public $modelName = '';
	public $defaultAction = 'admin';
	public $operates;
	public $operatesReturn = true;
	public $pkName = 'id';
	
	public function init() {
		if(!$this->modelName) {
			throw new CException('请指定modelName属性');
		}
	}
	
	public function getBreadcrumbs() {
		if(!$this->_breadcrumbs) {
			$route = Yii::app()->getController()->route;
			$nodes = explode('/', $route);
			$route = $baseRoute = '';
			$array = array();
			$enum = Yii::app()->enum;
			$count = count($nodes) - 1;
			$index = 1;
			foreach($nodes as $index=>$node) {
				if($index<2) {
					$baseRoute .= '/'.$node;
					continue;
				}
				$route .= '/'.$node;
				if($index == $count) {
					$name = $enum->lookup('system.operation', $node);
					
				} else {
					$name = $enum->lookup('breadcrumbs.admin', strtolower($route));
					
				}
				if(!$name) $name = $node;
				if($index == $count)
					$array[] = $name;	 
				else
					$array[$name] = array($baseRoute.$route);
				++$index;
			}
			$this->_breadcrumbs = $array;
		}
		return $this->_breadcrumbs;
	}
	
	public function getModelId() {
		if(isset($_GET[$this->pkName]))
			return $_GET[$this->pkName];
		return null;
	}
	
	public function modelProvider() {
		return array(
			'class' => 'ModelProvider',
			'modelName' => $this->modelName,
		);
	}
	
	public function loadModel($id = null) {
		$model = Yii::createComponent($this->modelProvider())->getModel($id);
		if(!$model) {
			$this->modelNotFound();
		}
		return $model;
	}
	
	public function modelNotFound() {
		$this->redirect(array('admin'));
	}
	
	public function actionUpdate($id) {
		$this->redirect($this->createUrl('edit', array(
			'id' => $id,
		)));
	}
	
	public function outerActions() {
		return array(
			'admin' => 'actions.admin',
			'edit' => 'actions.edit',
			'delete' => 'actions.delete',
			'view' => 'actions.view',
		);
	}
	
	public function readConfig($rpath) {
		return AdminModule::getConfig()->read($rpath, array(
			'controller' => $this,
			'model' => $this->loadModel($this->getModelId()),
		));
	}
	
	public function actions() {
		$outers = array();
		foreach($this->outerActions() as $name=>$rpath) {
			$outers[$name] = $this->readConfig($rpath);
		}
		return $outers;
	}
	

}

?>